package beer.coder.imageviewer.handler;

import javafx.event.EventHandler;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;

/**
 * TODO
 *
 * @author amath0312
 * @version 1.0
 * @date 2020-11-01 12:29
 */
public class ImageViewDraggedHandler implements EventHandler<MouseEvent> {

  public static final double MARGIN = 0d;

  boolean isDragging = false;
  double sourceX;
  double sourceY;
  ImageView imageView;

  public ImageViewDraggedHandler(ImageView imageView) {
    this.imageView = imageView;
  }

  @Override
  public void handle(MouseEvent event) {
    if (event.getEventType() == MouseEvent.MOUSE_PRESSED
        && event.getButton() == MouseButton.PRIMARY) {
      isDragging = true;
      sourceX = event.getScreenX();
      sourceY = event.getScreenY();
    } else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
      if (isDragging) {
        double dx = event.getScreenX() - sourceX;
        double dy = event.getScreenY() - sourceY;

        imageView.setLayoutX(imageView.getLayoutX() + dx);
        imageView.setLayoutY(imageView.getLayoutY() + dy);

        double boundWidth = imageView.getParent().getLayoutBounds().getWidth();
        double boundHeight = imageView.getParent().getLayoutBounds().getHeight();

        double imageWidth = imageView.getFitWidth() * imageView.getScaleX();
        double imageHeight = imageView.getFitHeight() * imageView.getScaleY();

        double boundX1 = MARGIN;
        double boundX2 = -(imageWidth - boundWidth) - MARGIN;
        double minX = Math.min(boundX1, boundX2);
        double maxX = Math.max(boundX1, boundX2);

        double boundY1 = MARGIN;
        double boundY2 = -(imageHeight - boundHeight) - MARGIN;
        double minY = Math.min(boundY1, boundY2);
        double maxY = Math.max(boundY1, boundY2);

        if (imageView.getLayoutX() < minX) {
          imageView.setLayoutX(minX);
        }
        if (imageView.getLayoutX() > maxX) {
          imageView.setLayoutX(maxX);
        }
        if (imageView.getLayoutY() < minY) {
          imageView.setLayoutY(minY);
        }
        if (imageView.getLayoutY() > maxY) {
          imageView.setLayoutY(maxY);
        }

        sourceX = event.getScreenX();
        sourceY = event.getScreenY();
      }
    } else if (event.getEventType() == MouseEvent.MOUSE_RELEASED) {
      isDragging = false;
      sourceX = -1;
      sourceY = -1;
    }
  }
}
